#region Usings

using System;
using Newtonsoft.Json;

#endregion

namespace Karma.Framework.Core.Serialization.Json.Converters
{
    public class EnumConverter<T> : JsonConverter where T : struct
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof (T).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType)
        {
            var e = reader.Value.ToString();
            return Enum.Parse(typeof (T), e, true);
        }

        public override void WriteJson(JsonWriter writer, object value)
        {
            if (value is T)
            {
                var e = (T) value;
                //writer.WriteValue(e.ToString());
                writer.WriteValue(Convert.ToInt32(e));
            }
            else
            {
                throw new Exception("Unexpected value when converting enumeration.");
            }
        }
    }
}